using MediatR;
using Microsoft.AspNetCore.Mvc;
using S.M.SmartMedical.API.Write.Application.Command;
using S.M.SmartMedical.Domain.DTOs;
using S.M.SmartMedical.ErrorCode;

namespace S.M.SmartMedical.API.Write.Controllers
{
    /// <summary>
    /// 轮播图管理控制器（写操作）
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class CarouselController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<CarouselController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator">中介者</param>
        /// <param name="logger">日志记录器</param>
        public CarouselController(IMediator mediator, ILogger<CarouselController> logger)
        {
            _mediator = mediator;
            _logger = logger;
        }

        /// <summary>
        /// 创建轮播图
        /// </summary>
        /// <param name="carouselCreateDto">轮播图创建信息</param>
        /// <returns>创建结果</returns>
        [HttpPost]
        public async Task<APIResult<CarouselDto>> Create([FromBody] CarouselCreateDto carouselCreateDto)
        {
            try
            {
                _logger.LogInformation("接收到创建轮播图请求，标题：{Title}", carouselCreateDto.Title);

                // 验证模型
                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Values
                        .SelectMany(v => v.Errors)
                        .Select(e => e.ErrorMessage)
                        .ToList();

                    _logger.LogWarning("创建轮播图参数验证失败：{Errors}", string.Join(", ", errors));

                    return new APIResult<CarouselDto>
                    {
                        Code = APIEnum.Fail,
                        Message = string.Join(", ", errors),
                        Data = null!
                    };
                }

                // 发送创建轮播图命令
                var command = new CreateCarouselCommand(carouselCreateDto);
                var result = await _mediator.Send(command);

                _logger.LogInformation("创建轮播图请求处理完成，标题：{Title}，结果：{Code}",
                    carouselCreateDto.Title, result.Code);

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建轮播图接口异常，标题：{Title}", carouselCreateDto.Title);
                return new APIResult<CarouselDto>
                {
                    Code = APIEnum.Fail,
                    Message = "创建轮播图失败，系统异常",
                    Data = null!
                };
            }
        }

        /// <summary>
        /// 更新轮播图
        /// </summary>
        /// <param name="carouselUpdateDto">轮播图更新信息</param>
        /// <returns>更新结果</returns>
        [HttpPut]
        public async Task<APIResult<CarouselDto>> Update([FromBody] CarouselUpdateDto carouselUpdateDto)
        {
            try
            {
                _logger.LogInformation("接收到更新轮播图请求，ID：{Id}", carouselUpdateDto.Id);

                // 验证模型
                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Values
                        .SelectMany(v => v.Errors)
                        .Select(e => e.ErrorMessage)
                        .ToList();

                    _logger.LogWarning("更新轮播图参数验证失败：{Errors}", string.Join(", ", errors));

                    return new APIResult<CarouselDto>
                    {
                        Code = APIEnum.Fail,
                        Message = string.Join(", ", errors),
                        Data = null!
                    };
                }

                // 发送更新轮播图命令
                var command = new UpdateCarouselCommand(carouselUpdateDto);
                var result = await _mediator.Send(command);

                _logger.LogInformation("更新轮播图请求处理完成，ID：{Id}，结果：{Code}",
                    carouselUpdateDto.Id, result.Code);

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新轮播图接口异常，ID：{Id}", carouselUpdateDto.Id);
                return new APIResult<CarouselDto>
                {
                    Code = APIEnum.Fail,
                    Message = "更新轮播图失败，系统异常",
                    Data = null!
                };
            }
        }

        /// <summary>
        /// 删除轮播图
        /// </summary>
        /// <param name="id">轮播图ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id}")]
        public async Task<APIResult<bool>> Delete([FromRoute] int id)
        {
            try
            {
                _logger.LogInformation("接收到删除轮播图请求，ID：{Id}，类型：{Type}", id, id.GetType());

                // 验证ID有效性
                if (id <= 0)
                {
                    _logger.LogWarning("删除轮播图请求参数无效，ID：{Id}", id);
                    return new APIResult<bool>
                    {
                        Code = APIEnum.Fail,
                        Message = "无效的轮播图ID",
                        Data = false
                    };
                }

                // 发送删除轮播图命令
                var command = new DeleteCarouselCommand(id);
                var result = await _mediator.Send(command);

                _logger.LogInformation("删除轮播图请求处理完成，ID：{Id}，结果：{Code}，消息：{Message}",
                    id, result.Code, result.Message);

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除轮播图接口异常，ID：{Id}", id);
                return new APIResult<bool>
                {
                    Code = APIEnum.Fail,
                    Message = "删除轮播图失败，系统异常",
                    Data = false
                };
            }
        }

        /// <summary>
        /// 批量删除轮播图
        /// </summary>
        /// <param name="ids">轮播图ID数组</param>
        /// <returns>批量删除结果</returns>
        [HttpDelete("batch")]
        public async Task<APIResult<bool>> BatchDelete([FromBody] int[] ids)
        {
            try
            {
                _logger.LogInformation("接收到批量删除轮播图请求，IDs：{Ids}，数量：{Count}", 
                    string.Join(",", ids), ids?.Length ?? 0);

                // 验证参数
                if (ids == null || ids.Length == 0)
                {
                    _logger.LogWarning("批量删除轮播图参数无效，ID数组为空");
                    return new APIResult<bool>
                    {
                        Code = APIEnum.Fail,
                        Message = "请选择要删除的轮播图",
                        Data = false
                    };
                }

                // 验证所有ID有效性
                if (ids.Any(id => id <= 0))
                {
                    _logger.LogWarning("批量删除轮播图参数包含无效ID");
                    return new APIResult<bool>
                    {
                        Code = APIEnum.Fail,
                        Message = "包含无效的轮播图ID",
                        Data = false
                    };
                }

                // 批量执行删除
                var successCount = 0;
                var failCount = 0;

                foreach (var id in ids)
                {
                    try
                    {
                        var command = new DeleteCarouselCommand(id);
                        var result = await _mediator.Send(command);
                        
                        if (result.Code == APIEnum.OK)
                        {
                            successCount++;
                        }
                        else
                        {
                            failCount++;
                            _logger.LogWarning("批量删除中单个删除失败，ID：{Id}，原因：{Message}", id, result.Message);
                        }
                    }
                    catch (Exception ex)
                    {
                        failCount++;
                        _logger.LogError(ex, "批量删除中单个删除异常，ID：{Id}", id);
                    }
                }

                _logger.LogInformation("批量删除轮播图完成，成功：{SuccessCount}，失败：{FailCount}", 
                    successCount, failCount);

                if (successCount == ids.Length)
                {
                    return new APIResult<bool>
                    {
                        Code = APIEnum.OK,
                        Message = $"成功删除 {successCount} 个轮播图",
                        Data = true
                    };
                }
                else if (successCount > 0)
                {
                    return new APIResult<bool>
                    {
                        Code = APIEnum.Fail,
                        Message = $"部分删除成功：{successCount} 个成功，{failCount} 个失败",
                        Data = false
                    };
                }
                else
                {
                    return new APIResult<bool>
                    {
                        Code = APIEnum.Fail,
                        Message = "所有轮播图删除失败",
                        Data = false
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除轮播图接口异常");
                return new APIResult<bool>
                {
                    Code = APIEnum.Fail,
                    Message = "批量删除轮播图失败，系统异常",
                    Data = false
                };
            }
        }
    }
}